# treeview1.pyA
from pprint import *
from wax import *
import os
import rsbmodel
from path import path
twist_buttons = 1
# set to 1 to show Mac-style buttons... if your system supports them

def filltree(tree):
    #root = tree.AddRoot("the root item")
#    for i in range(10):
#        child = tree.AppendItem(root, "Item %d" % (i,))
#        for j in range(5):
#            grandchild = tree.AppendItem(child, "Item %d" % (i*10+j))
#
#    print [x for x in tree.GetChildNodes(root)]
#
#    d = {
#        "Hans": {
#            "age": 30,
#            "sign": "Aquarius",
#            "job": "programmer",
#        },
#        "Fred": {
#            "age": "unknown",
#            "sign": "unknown",
#            "shoe size": "unknown",
#        },
#        "Old Guy John": {
#            "age": "old",
#            "sign": "Aquarius",
#        },
#        "Bob": {
#            "sign": "Taurus",
#            "job": "proprietor",
#        },
#        "Christine": {
#            "age": 17,
#            "sign": "Aries",
#            "job": "cashier",
#        }
#    }
#
#    stuff = tree.AppendItem(root, "stuff")
#    tree.LoadFromDict(stuff, d)

    return tree



def find_node(tree, nodepath, create = False):
    cur = tree.GetRootItem()
    els = nodepath.split('/')
    #print "els",els
    for pathel in els:
        #print "trying",pathel
        childs = ((tree.GetItemText(c), c) for c in tree.GetChildNodes(cur))
        #pprint (list(childs))
        for name,c in childs:
            #print name,"against",pathel
            if name == pathel:
                #print "traversing",name,c
                cur = c
                break
        else:
            if not create:
                #print "notcreate, return"
                return None
            # need to create and proceed
            
            newnode = tree.AppendItem(cur,pathel)
            cur = newnode
            #print "created",pathel,cur
    return cur

    
class MainFrame(Frame):

    def Body(self):
        self.bu = bu
        
        self.rootname = 'unnamed'
        menubar = MenuBar(self)

        menu1 = Menu(self)
        menu1.Append("&Save", self.DoSave, "Save changes" )
        menu1.Append("&Open", self.DoLoad, "Load" )
        menu1.Append("&New", self.DoNew, "New" )
        menubar.Append(menu1, "&File")
        
        splitter = Splitter(self, size=(500, 300))
        self.treeview = TreeView(splitter, twist_buttons=twist_buttons, has_buttons=1)
        self.treeview.OnSelectionChanged = self.OnTreeSelectionChanged
        self.treeview.OnItemActivated = self.OnTreeDoubleClick
        
        self.infobox = ListView(splitter, columns = ['Key','Val'], rules = 'both')
        self.infobox.SetColumnWidths([-1,500])
        self.infobox.OnItemDoubleClick = self.OnListItemDoubleClick
        #self.textbox = TextBox(splitter, multiline=1)
        splitter.Split(self.treeview, self.infobox, direction='v')
        self.AddComponent(splitter, expand='both')
        #filltree(self.treeview)
        #find_node(self.treeview,'hello/dummy',create=1)
        #find_node(self.treeview,'hello/dude',create=1)
        self.Pack()
        filedrop = FileDropTarget(self.treeview, event=self.dropfiles)
        
        self.bu.add_newitem_listener(self.newitem)
        self.DoNew(None)
    def DoNew(self,ev):
        self.rootname = 'unnamed'
        
        self.resetitems()
    def DoSave(self,ev):
        
        if self.rootname == 'unnamed':
            dlg = FileDialog(self, save=1)
            dlg.SetWildcard("Resbundles (*.rbu)|*.rbu")
            try:
                result = dlg.ShowModal()
                if result == 'ok':
                    self.rootname = dlg.GetPaths()[0]
                    if not self.rootname.endswith('.rbu'):
                        self.rootname = self.rootname + '.rbu'
            finally:
                dlg.Destroy()
        
        if self.rootname != 'unnamed':
            print 'saveto',self.rootname
            self.bu.save(self.rootname)
    
    def DoLoad(self,ev):

        dlg = FileDialog(self, open=1)
        try:
            dlg.SetWildcard("Resbundles (*.rbu)|*.rbu")
            
            result = dlg.ShowModal()
            if result == 'ok':
                filename = dlg.GetPaths()[0]
                self.rootname = filename
                self.resetitems()
                self.bu.load(filename)
                self.treeview.Expand(self.treeview.GetRootItem())

        finally:
            dlg.Destroy()
        
    def resetitems(self):
        self.treeview.DeleteAllItems()
        self.treeview.AddRoot(self.rootname)
        
        
    def newitem(self, path, res):
        cat = find_node(self.treeview, path, create=1)
        node = self.treeview.AppendItem(cat, res.name)
        self.treeview.SetPyData(node, res)
        
    def dropfiles(self, x,y,files):
        print "drop",files
        for f in files:
            p = path(f)
            if p.isfile():
                self.bu.drop_item(f)
            elif p.isdir():
                self.dropfiles(x,y,p.walkfiles())
        
    def OnTreeSelectionChanged(self, event):
        item = event.GetItem()
        data = self.treeview.GetPyData(item)
        print "disp",data
        if data is None:
            data = {}
        self.infobox.DeleteAllItems()
        if isinstance(data,rsbmodel.Resource):
            for k,v in data.data().items():
                self.infobox.AppendRow(k,v)
        else:
            self.infobox.AppendRow('repr',repr(data))
        
        #self.textbox.Clear()
        #self.textbox.AppendText(str(data))
        event.Skip()
    def OnListItemDoubleClick(self,event):
        print event
    def OnTreeDoubleClick(self,ev):
        print "tree dbl",ev
        item = ev.GetItem()
        obj = self.treeview.GetPyData(item)
        obj.activate()
        


def main():
    global bu
    bu = rsbmodel.ResourceBunch()
    bu.add_recognizer( rsbmodel.basic_file_recognizer )
    
    app = Application(MainFrame, direction='h')
    app.Run()

main()